<script setup lang="ts">
import { PostloginPasswordAPI } from '@/api/common'
import { useUserStore } from '@/store'
import type { PostloginPasswordParams } from '@/types/common'
import { ref } from 'vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})

const FormData = ref<PostloginPasswordParams>({
  mobile: '13230000061',
  password: 'abc12345',
})

const FormRules = ref<UniHelper.UniFormsRules>({
  mobile: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的的手机号' },
    ],
  },
  password: {
    rules: [
      { required: true, errorMessage: '请输入密码' },
      { pattern: /^\d{6}$/, errorMessage: '验证码格式错误' },
    ],
  },
})

const isAgree = ref(false)
const formRef = ref()
const store = useUserStore()
// 表单提交
const onSubmit = async () => {
  if (!isAgree.value) {
    return uni.showToast({
      title: '请同意用户协议和隐私协议',
      icon: 'none',
    })
  }
  const res = await PostloginPasswordAPI(FormData.value)
  console.log(res)
  store.setToken(res.data.token)
  store.setUserInfo(res.data)
  uni.showToast({
    title: '登录成功',
    icon: 'success',
  })
  uni.switchTab({
    url: '/pages/index/index',
  })
}

// 清除Token
store.clearToken()
store.clearUserInfo()
// 关闭所有页面
uni.reLaunch({
  url: '/pages/login/login',
})
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :rules="FormRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="FormData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        v-model="FormData.password"
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
    {{ FormData }}
  </uni-forms>
</template>

<style lang="scss">
@import '../styles.scss';
</style>
